package com.cyl.order.service.impl;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

import com.cyl.order.domain.TOrderAmount;
import com.cyl.order.mapper.TOrderDetailsMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.UUID;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.cyl.order.domain.TOrderDetails;
import com.cyl.order.mapper.TOrderInfoMapper;
import com.cyl.order.domain.TOrderInfo;
import com.cyl.order.service.ITOrderInfoService;

import javax.servlet.http.HttpServletResponse;

/**
 * 订单信息管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-14
 */
@Service
public class TOrderInfoServiceImpl implements ITOrderInfoService 
{
    @Autowired
    private TOrderInfoMapper tOrderInfoMapper;

    @Autowired
    private TOrderDetailsMapper tOrderDetailsMapper;

    /**
     * 查询订单信息管理
     * 
     * @param id 订单信息管理主键
     * @return 订单信息管理
     */
    @Override
    public TOrderInfo selectTOrderInfoById(Long id)
    {
        TOrderInfo tOrderInfo = tOrderInfoMapper.selectTOrderInfoById(id);
        TOrderDetails tOrderDetails = new TOrderDetails();
        tOrderDetails.setOrderId(tOrderInfo.getOrderId());
        List<TOrderDetails> tOrderDetailsList = tOrderDetailsMapper.selectTOrderDetailsList(tOrderDetails);
        tOrderInfo.setTOrderDetailsList(tOrderDetailsList);

        return tOrderInfo;
    }

    /**
     * 查询订单信息管理列表
     * 
     * @param tOrderInfo 订单信息管理
     * @return 订单信息管理
     */
    @Override
    public List<TOrderInfo> selectTOrderInfoList(TOrderInfo tOrderInfo)
    {
        return tOrderInfoMapper.selectTOrderInfoList(tOrderInfo);
    }

    /**
     * 新增订单信息管理
     * 
     * @param tOrderInfo 订单信息管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTOrderInfo(TOrderInfo tOrderInfo)
    {
        LocalDateTime localDateTime = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        String orderId = "ZR002" + DateUtils.dateTimeNow();
        tOrderInfo.setOrderId(orderId);

        tOrderInfo.setCreateTime(localDateTime);
        int rows = tOrderInfoMapper.insertTOrderInfo(tOrderInfo);
        insertTOrderDetails(tOrderInfo);
        return rows;
    }

    /**
     * 修改订单信息管理
     * 
     * @param tOrderInfo 订单信息管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTOrderInfo(TOrderInfo tOrderInfo)
    {
        LocalDateTime localDateTime = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        tOrderInfo.setUpdateTime(localDateTime);
        tOrderInfoMapper.deleteTOrderDetailsByOrderId(tOrderInfo.getOrderId());
        insertTOrderDetails(tOrderInfo);
        return tOrderInfoMapper.updateTOrderInfo(tOrderInfo);
    }

    /**
     * 批量删除订单信息管理
     * 
     * @param ids 需要删除的订单信息管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTOrderInfoByIds(Long[] ids)
    {
        for (Long id : ids) {
            TOrderInfo tOrderInfo = tOrderInfoMapper.selectTOrderInfoById(id);
            tOrderInfoMapper.deleteTOrderDetailsByOrderId(tOrderInfo.getOrderId());
            tOrderInfoMapper.deleteTOrderInfoById(id);
        }
        return 1;
    }

    /**
     * 删除订单信息管理信息
     * 
     * @param id 订单信息管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTOrderInfoById(Long id)
    {
        TOrderInfo tOrderInfo = tOrderInfoMapper.selectTOrderInfoById(id);

        tOrderInfoMapper.deleteTOrderDetailsByOrderId(tOrderInfo.getOrderId());
        return tOrderInfoMapper.deleteTOrderInfoById(id);
    }

    @Override
    public void exportOrderInfo(Long id, HttpServletResponse response) {
        TOrderInfo tOrderInfo = selectTOrderInfoById(id);
        // 打开excel模板,获取第一个工作表。
        String name = "订单信息模板.xlsx";
        try {
            FileInputStream templateFile = new FileInputStream(new File(RuoYiConfig.getTemplate()+ name));//pfTemporaryTemplate:模板路径
            Workbook templateWorkbook = null;
            templateWorkbook = new XSSFWorkbook(templateFile);
            Sheet templateSheet = templateWorkbook.getSheetAt(0);

            Row row1 =  templateSheet.getRow(1);
            row1.getCell(9).setCellValue(tOrderInfo.getOrderId());
            Row row2 =  templateSheet.getRow(2);
            row2.getCell(9).setCellValue(tOrderInfo.getOrderDate());

            Row row5 =  templateSheet.getRow(5);
            row5.getCell(4).setCellValue("参数：" + tOrderInfo.getPitou());
            row5.getCell(7).setCellValue(tOrderInfo.getCmsAddress());
            row5.getCell(9).setCellValue(tOrderInfo.getAcceptanceTime());
            Row row6 =  templateSheet.getRow(6);
            row6.getCell(3).setCellValue(tOrderInfo.getCmsName());

            String str = "重量：" + tOrderInfo.getCueWeight() + "/长度：" + tOrderInfo.getCueLength()
                    + "/握把" + tOrderInfo.getCueGrip() + "/重心:" + tOrderInfo.getCueBarycenter();
            row6.getCell(4).setCellValue(str);

            row6.getCell(7).setCellValue(tOrderInfo.getCmsPhone());


            Row row19 =  templateSheet.getRow(19);
            BigDecimal total = new BigDecimal(tOrderInfo.getTotalAmount()).setScale(2, RoundingMode.HALF_UP);
            row19.getCell(4).setCellValue( "¥" + total);
            BigDecimal paid = new BigDecimal(tOrderInfo.getPaidAmount()).setScale(2, RoundingMode.HALF_UP);

            row19.getCell(7).setCellValue( "¥" + paid);

            Row row21 =  templateSheet.getRow(21);
            row21.getCell(2).setCellValue("送货单位及经手人：" + tOrderInfo.getSalesperson());
            row21.getCell(7).setCellValue("收货单位及收货人：" + tOrderInfo.getCmsName());


            List<TOrderDetails> tOrderDetailsList = tOrderInfo.getTOrderDetailsList();

            for (int i = 0; i < tOrderDetailsList.size(); i++) {
                Row row =  templateSheet.getRow(11+i);
                row.getCell(2).setCellValue(i+1);
                row.getCell(3).setCellValue(tOrderDetailsList.get(i).getGoodsName());
                row.getCell(4).setCellValue(tOrderDetailsList.get(i).getSpecifications());
                row.getCell(5).setCellValue(tOrderDetailsList.get(i).getUnit());
                row.getCell(6).setCellValue(tOrderDetailsList.get(i).getNumber());
                row.getCell(7).setCellValue(tOrderDetailsList.get(i).getUnitPrice());
                row.getCell(8).setCellValue(tOrderDetailsList.get(i).getPrice());
                row.getCell(9).setCellValue(tOrderDetailsList.get(i).getRemark());
            }


            //生成文件路径
            String newFileName = tOrderInfo.getCmsName() + "订单信息";
            newFileName = newFileName + "_" +  UUID.randomUUID().toString().replace("-","") + ".xlsx";
            // 保存excel文件
            FileOutputStream fileOutputStream = new FileOutputStream(getAbsoluteFile(newFileName));
            templateWorkbook.write(fileOutputStream);
            fileOutputStream.close();

            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(newFileName,"UTF-8") + "\"");
            response.setCharacterEncoding("utf-8");

            templateWorkbook.write(outputStream);


            // 关闭excel模板
            templateFile.close();
            templateWorkbook.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public AjaxResult queryAmount() {
        TOrderAmount tOrderAmount = tOrderInfoMapper.queryAmount();
        return AjaxResult.success(tOrderAmount);
    }

    /**
     * 新增订单明细信息
     * 
     * @param tOrderInfo 订单信息管理对象
     */
    public void insertTOrderDetails(TOrderInfo tOrderInfo)
    {
        List<TOrderDetails> tOrderDetailsList = tOrderInfo.getTOrderDetailsList();
        String id = tOrderInfo.getOrderId();
        if (StringUtils.isNotNull(tOrderDetailsList))
        {
            List<TOrderDetails> list = new ArrayList<TOrderDetails>();
            for (TOrderDetails tOrderDetails : tOrderDetailsList)
            {
                tOrderDetails.setOrderId(id);
                list.add(tOrderDetails);
            }
            if (list.size() > 0)
            {
                tOrderInfoMapper.batchTOrderDetails(list);
            }
        }
    }
    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename)
    {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

}
